package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.UserMapper;
import com.heima.admin.service.UserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.AppJwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, AdUser> implements UserService {
    /**
     * 登录实现
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1. 检查参数(用户名密码缺一不可)
        if(StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2. 查询用户信息,如果不存在用户,返回error
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"账号不存在");
        }

        //3. 校验密码
        String pwd = user.getPassword();
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if(!pwd.equalsIgnoreCase(inputPwd)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //4. 修改最近登录时间
        user.setLoginTime(new Date());
        updateById(user);

        //5. 生成token并返回
        String token = AppJwtUtil.getToken(user.getId());
        Map resultMap = new HashMap<>();
        AdUserVo userVo = new AdUserVo();
        BeanUtils.copyProperties(user,userVo);
        resultMap.put("user",userVo);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 注册实现
     * @param user
     * @return
     */
    @Override
    public ResponseResult register(AdUser user) {
        //1.参数校验
        if (StringUtils.isEmpty(user.getName())
                || StringUtils.isEmpty(user.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不能为空");
        }
        // 判断注册的用户名是否存在
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery();
        AdUser adUser = getOne(wrapper.eq(AdUser::getName,user.getName()));
        if(adUser!=null){
            ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"该用户名已存在");
        }
        // 用户的密码加密规则是：MD5（密码 + salt）
        String salt = RandomStringUtils.randomAlphanumeric(8);
        String password = user.getPassword()+salt;
        user.setPassword( DigestUtils.md5DigestAsHex(password.getBytes()) );
        user.setSalt(salt);
        //设置最新登录的时间
        user.setCreatedTime(new Date());
        user.setStatus(9);
        save(user);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
